// 📁 文件位置：config/webpack.common.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  // 入口文件
  entry: './src/index.js',
  
  // 输出配置
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].js',
    clean: true
  },
  
  // 模块处理规则
  module: {
    rules: [
      // JavaScript 处理
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            cacheDirectory: true,
            // 开发环境禁用压缩以提升速度
            cacheCompression: false
          }
        }
      },
      
      // 图片处理
      {
        test: /\.(png|jpe?g|gif|svg)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'images/[name].[hash:8][ext]'
        },
        parser: {
          dataUrlCondition: {
            maxSize: 8 * 1024 // 8KB
          }
        }
      },
      
      // 字体处理
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'fonts/[name].[hash:8][ext]'
        }
      }
    ]
  },
  
  // 插件配置
  plugins: [
    // HTML 模板插件
    new HtmlWebpackPlugin({
      template: './public/index.html',  //源头
      filename: 'index.html',           //打包以后的名称
      inject: 'body'                    //将js 注入到body的底部
    }),
    
    // CSS 提取插件
    new MiniCssExtractPlugin({
      filename: '[name].css'
    })
  ],
  
  // 路径解析
  resolve: {
    alias: {
      '@': path.resolve(__dirname, '../src'),
      '@components': path.resolve(__dirname, '../src/components'),
      '@utils': path.resolve(__dirname, '../src/utils'),
      '@assets': path.resolve(__dirname, '../src/assets')
    },
    extensions: ['.js', '.json'],
    // 优化模块查找
    modules: [path.resolve(__dirname, '../node_modules')],
    // 如果不使用符号链接，可以禁用以提升性能
    symlinks: false,
    // Node.js polyfills fallback
    fallback: {
      "events": require.resolve("events/")
    }
  }
};